package com.ceadeal.admin.web.user;

import com.ceadeal.admin.service.user.UserService;
import com.ceadeal.admin.vo.param.SearchParams;
import com.ceadeal.admin.common.consts.Constant;
import com.ceadeal.admin.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 功能描述: 用户web
 * @param
 * @return
 * @throws
 *
 * @author Yzw
 * @date 2017-03-07 15:00:15
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public String list() {
        return "/user/list";
    }

    @ResponseBody
    @PostMapping("/listData")
    public Object listData(SearchParams sp) {
        return this.userService.findByPaging(sp);
    }

    @GetMapping("/view")
    public String view(HttpServletRequest request, Long id) {
        User user = this.userService.find(id);
        request.setAttribute("user", user);
        return "/user/view";
    }

    @GetMapping("/edit")
    public String edit(HttpServletRequest request, Long id) {
        User user = new User();
        if (id != null) {
            user = this.userService.find(id);
        }
        request.setAttribute("user", user);
        return "/user/edit";
    }

    @PostMapping("/save")
    public String save(User user, RedirectAttributes redirectAttributes) {
        try {
            this.userService.saveHandler(user);
            redirectAttributes.addFlashAttribute("flashMessage", Constant.OPERATE_SUCCESS);
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("flashMessage", Constant.OPERATE_ERROR);
            log.error(e.getMessage());
        }
        return "redirect:/user/list";
    }

    @ResponseBody
    @GetMapping("/checkUserName")
    public String checkUserName(String userName) {
        return this.userService.findByUserName(userName) == null ? "true" : "false";
    }

}
